import Footer from '@/components/Footer';
import { login } from '@/services/api';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {
  LoginForm,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { Helmet, useModel } from '@umijs/max';
import { message } from 'antd';
import md5 from 'js-md5';
import { flushSync } from 'react-dom';
function Login() {
  const { initialState, setInitialState } = useModel('@@initialState');
  //清除cookie,3个值都为空，天数为负1天就好了
  // const clearCookie = (c_name, exdays) => setCookie(c_name, "", "", exdays);
  //设置cookie
  const setCookie = (
    c_name: string,
    c_pwd: string,
    c_rem: string,
    exdays: number,
  ) => {
    const exdate = new Date(); //获取时间
    if (c_rem === 'false') {
      exdate.setTime(exdate.getTime() - 1000);
    } else {
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
    }
    //字符串拼接cookie
    window.document.cookie = `username=${c_name};path=/;expires=${exdate.toUTCString()}`;
    window.document.cookie = `password=${c_pwd};path=/;expires=${exdate.toUTCString()}`;
    window.document.cookie = `remember=${c_rem};path=/;expires=${exdate.toUTCString()}`;
  };

  //读取cookie
  const getCookie = () => {
    if (document.cookie.length > 0) {
      const arr = document.cookie.split('; '); //这里显示的格式需要切割一下自己可输出看下
      const obj = {
        username: '',
        password: '',
        remember: true,
      };
      for (let i = 0; i < arr.length; i++) {
        let arr2 = arr[i].split('='); //再次切割
        // 判断查找相对应的值
        //调用无状态子组件的方法,赋值上去
        if (arr2[0] === 'username') {
          obj.username = arr2[1];
        } else if (arr2[0] === 'password') {
          obj.password = arr2[1];
        } else if (arr2[0] === 'remember') {
          obj.remember = arr2[1] === 'true' ? true : false;
        }
      }
      return obj;
    }
  };
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    console.log(userInfo);
    if (userInfo) {
      flushSync(() => {
        setInitialState((s: any) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  const handleSubmit = async (values: any) => {
    try {
      const data = {
        ...values,
        password: md5(values.password),
      };
      // 登录
      const res = await login(data);
      if (res.msg) {
        message.error(res.msg);
        return;
      }
      message.success('登录成功！');
      localStorage.setItem('token', res.data.token);
      await fetchUserInfo();

      const urlParams = new URL(window.location.href).searchParams;
      // history.push(urlParams.get('redirect') || '/');
      window.location.href = urlParams.get('redirect') || '/';
      return;
    } catch (error) {
      message.error('登录失败，请重试！');
    }
  };

  return (
    <div>
      <Helmet>
        <title>{`登录页 - ${initialState?.title}`}</title>
      </Helmet>
      {/* <Lang /> */}
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
            marginTop: 40,
          }}
          // logo={<img alt="logo" src="/logo.png" />}
          title={initialState?.title}
          // subTitle={intl.formatMessage({ id: '' })}
          initialValues={getCookie()}
          actions={
            [
              // <FormattedMessage
              //   key="loginWith"
              //   id="pages.login.loginWith"
              //   defaultMessage="其他登录方式"
              // />,
              // <ActionIcons key="icons" />,
            ]
          }
          onFinish={async (values) => {
            setCookie(
              values.username,
              values.password,
              values.remember ? 'true' : 'false',
              7,
            );
            await handleSubmit(values);
          }}
        >
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
              }}
              placeholder={'请输入用户名'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder={'请输入密码！'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>

          {/* {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />}
          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined />,
                }}
                name="mobile"
                placeholder={intl.formatMessage({
                  id: 'pages.login.phoneNumber.placeholder',
                  defaultMessage: '手机号',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.phoneNumber.required"
                        defaultMessage="请输入手机号！"
                      />
                    ),
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: (
                      <FormattedMessage
                        id="pages.login.phoneNumber.invalid"
                        defaultMessage="手机号格式错误！"
                      />
                    ),
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.captcha.placeholder',
                  defaultMessage: '请输入验证码',
                })}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${intl.formatMessage({
                      id: 'pages.getCaptchaSecondText',
                      defaultMessage: '获取验证码',
                    })}`;
                  }
                  return intl.formatMessage({
                    id: 'pages.login.phoneLogin.getVerificationCode',
                    defaultMessage: '获取验证码',
                  });
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.captcha.required"
                        defaultMessage="请输入验证码！"
                      />
                    ),
                  },
                ]}
                onGetCaptcha={async (phone) => {
                  const result = await getFakeCaptcha({
                    phone,
                  });
                  if (!result) {
                    return;
                  }
                  message.success('获取验证码成功！验证码为：1234');
                }}
              />
            </>
          )} */}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="remember">
              记住密码
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              忘记密码
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
}
Login.layout = false;
export default Login;
